package cn.faifai.tagapi.service.BackgroundServices.FileWatcher.impl;

import cn.faifai.framework.jna.faifaiKernel32;
import cn.faifai.tagapi.service.BackgroundServices.FileWatcher.FileWatcher;
import com.sun.jna.Memory;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.WinBase;
import com.sun.jna.platform.win32.WinNT;
import com.sun.jna.ptr.IntByReference;

import java.io.IOException;
import java.nio.file.Path;

@Deprecated
public class WindowsFileWatcherNative implements FileWatcher {

    public WindowsFileWatcherNative() {
    }

    @Override
    public void run(Path path) throws IOException {
        String pathToWatch = "\\\\?\\" + path.toString(); // 替换为目标路径

        WinNT.HANDLE dirHandle = faifaiKernel32.INSTANCE.CreateFileA(
                pathToWatch,
                new WinNT.DWORD(0x80000000 | 0x40000000), // GENERIC_READ | GENERIC_WRITE
                new WinNT.DWORD(0x00000001 | 0x00000002 | 0x00000004), // FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE
                null, new WinNT.DWORD(WinNT.OPEN_EXISTING),
                new WinNT.DWORD(0x02000000), // FILE_FLAG_BACKUP_SEMANTICS
                null);

        if (!dirHandle.equals(WinBase.INVALID_HANDLE_VALUE)) {
            byte[] buffer = new byte[1024];
            IntByReference bytesReturned = new IntByReference();
            Pointer pointer = new Memory(Native.getNativeSize(Long.TYPE) * buffer.length);
            boolean result = faifaiKernel32.INSTANCE.ReadDirectoryChangesW(
                    dirHandle,
                    pointer,
                    new WinNT.DWORD(buffer.length),
                    true,
                    new WinNT.DWORD(WinNT.FILE_NOTIFY_CHANGE_FILE_NAME | WinNT.FILE_NOTIFY_CHANGE_LAST_WRITE),
                    bytesReturned,
                    null,
                    null);

            if (result) {
                System.out.println("Changes detected.");
                // 解析pointer中的FILE_NOTIFY_INFORMATION结构体
            } else {
                System.err.println("Failed to read directory changes.");
            }
        } else {
            throw new IOException("Failed to open file. Error code: " + Native.getLastError());
        }
    }

    public static void main(String[] args) throws IOException {
        WindowsFileWatcherNative windowsFileWatcherNative = new WindowsFileWatcherNative();
        windowsFileWatcherNative.run(Path.of("C:\\HardLinks"));
    }
}
